﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Thor.Common
{
    public class TimeZoneManager
    {
        public List<TimeZone> GetTimeZones()
        {
            List<Thor.Common.TimeZone> timeZones = new List<Thor.Common.TimeZone>();

            foreach (var timeZone in TimeZoneInfo.GetSystemTimeZones().OrderByDescending(tz => tz.BaseUtcOffset.Hours))
                timeZones.Add(new Thor.Common.TimeZone() { Name = timeZone.Id });

            return timeZones;
        }
         
        public TimeZoneInfo GetTimeZoneInfoById(string id)
        {
            var timeZoneInfo = (from t in TimeZoneInfo.GetSystemTimeZones()
                     where t.Id == id
                     select t).FirstOrDefault();

            if (timeZoneInfo == null)
                return TimeZoneInfo.Utc;
            else
                return timeZoneInfo;
        }

        public DateTime ConvertTimeFromUtc(DateTime dateTime, string timeZoneId)
        {
            var timeZone = GetTimeZoneInfoById(timeZoneId);

            if (timeZone == TimeZoneInfo.Utc)
                return dateTime;
            else
                return TimeZoneInfo.ConvertTimeFromUtc(dateTime, timeZone);
        }

        public DateTime ConverTimeToUtc(DateTime dateTime, string timeZoneId)
        {
            var timeZone = GetTimeZoneInfoById(timeZoneId);

            if (timeZone == TimeZoneInfo.Utc)
                return dateTime;
            else
                return TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZone);
        }
    }
}
